import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/datas/game_item.dart';
import 'package:flutter_syt/domain/main_page.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/datas/venue_item.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';

class EventScheduleFilter extends StatefulWidget {
  EventScheduleFilter({Key? key, required this.data}) : super(key: key);

  final EventFilterData data;

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _EventScheduleFilterState();
  }
}

class _EventScheduleFilterState extends State<EventScheduleFilter> {
  VenueItem selectVenue = VenueItem({"id": "", "name": S().All});
  GameDetail selectMatch = GameDetail({"id": "", "discipline_name": S().All});
  EventStateData selectState = EventStateData(S().All, '0');

  @override
  void initState() {
    selectVenue = widget.data.selectVenue;
    selectMatch = widget.data.selectMatch;
    selectState = widget.data.selectState;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var screenSize = MediaQuery.of(context).size;
    var weatherHeight = 35; // 天气区高度
    var headerHeight = 60; // 父类滚动条的高度
    var topHeight =
        weatherHeight + kCurrentAppSafeInset.top + headerHeight; //顶部距离
    var bottomHeight =
        kBottomNavigationBarHeight + kCurrentAppSafeInset.bottom; // 底部距离
    var contentHeight = 64.5 + 40; //头部的高度和底部确认按钮的高度。
    var canUseHeight = screenSize.height -
        topHeight -
        bottomHeight -
        contentHeight -
        90; //内容可用区 保持底部90距离
    return Column(
      children: [
        titleWidget(),
        Container(
          height: canUseHeight,
          color: Colors.white,
          padding: EdgeInsets.symmetric(horizontal: 15),
          child: CustomScrollView(
            slivers: [
              _gameSection(),
              _venueSection(),
              _stateSection(),
            ],
            reverse: false,
          ),
        ),
        _bottomView()
      ],
    );
  }

  Widget titleWidget() {
    return Container(
      height: 40,
      color: Colors.white,
      padding: EdgeInsets.only(left: 15),
      child: Row(
        children: [
          Text(
            S.of(context).schedule,
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
          ),
          Spacer(),
          IconButton(
            onPressed: ClickUtils.debounce(() {
              _onCancel();
            }),
            icon: Icon(Icons.close),
          ),
        ],
      ),
    );
  }

  Widget _venueSection() {
    Widget _item(VenueItem model) {
      return GestureDetector(
        onTap: ClickUtils.debounce(() {
          if (selectVenue.id != model.id) {
            selectVenue = model;
          }
          setState(() {});
        }),
        child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              color: (model.id == selectVenue.id)
                  ? ThemeColor.primaryColor
                  : Color(0xffF4F4F4),
            ),
            alignment: Alignment.center,
            child:
                // Stack(
                //   children: [
                //     Positioned(
                //         top: 6,
                //         right: 0,
                //         left: 0,
                //         child:
                Text(
              model.name,
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 14,
                fontWeight: (selectVenue.id == model.id)
                    ? FontWeight.w600
                    : FontWeight.w400,
                fontFamily: 'PingFangSC-Medium, PingFang SC',
              ),
              overflow: TextOverflow.ellipsis,
            )
            // ),
            //     if (model.id == selectVenue.id)
            //       Positioned(
            //         right: 0,
            //         bottom: 0,
            //         child: Image.asset(
            //           "assets/icons/icon_event_filter.png",
            //           width: 16,
            //           height: 13,
            //         ),
            //       ),
            //   ],
            // ),
            ),
      );
    }

    return Container(
      child: SliverStickyHeader(
        header: Container(
          color: Colors.white,
          height: 42,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                S.of(context).Venues,
                style: TextStyle(
                  fontWeight: FontWeight.w500, fontSize: 14,
                  // fontFamily: 'PingFangSC-Regular, PingFang SC'
                ),
              )
            ],
          ),
        ),
        sliver: SliverGrid(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 1,
              crossAxisSpacing: 8,
              mainAxisSpacing: 10,
              mainAxisExtent: 32),
          delegate: SliverChildBuilderDelegate(
            (context, i) => _item(widget.data.venueList[i]),
            childCount: widget.data.venueList.length,
          ),
        ),
      ),
    );
  }

  Widget _gameSection() {
    Widget _item(GameDetail model) {
      return GestureDetector(
        onTap: ClickUtils.debounce(() {
          if (selectMatch.id != model.id) {
            selectMatch = model;
            setState(() {});
          }
        }),
        child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              color: (selectMatch.id == model.id)
                  ? ThemeColor.primaryColor
                  : Color(0xffF4F4F4),
            ),
            alignment: Alignment.center,
            child:
                // Stack(
                //   children: [
                //     Positioned(
                //         top: 6,
                //         right: 0,
                //         left: 0,
                //         child:
                Text(
              model.discipline_name,
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 14,
                fontWeight: (selectMatch.id == model.id)
                    ? FontWeight.w600
                    : FontWeight.w400,
                fontFamily: 'PingFangSC-Medium, PingFang SC',
              ),
              overflow: TextOverflow.ellipsis,
            )
            // ),
            // if (selectMatch.id == model.id)
            //   Positioned(
            //     right: 0,
            //     bottom: 0,
            //     child: Image.asset(
            //       "assets/icons/icon_event_filter.png",
            //       width: 16,
            //       height: 13,
            //     ),
            //   ),
            // ],
            // ),
            ),
      );
    }

    return Container(
      child: SliverStickyHeader(
        header: Container(
          color: Colors.white,
          height: 42,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                S.of(context).Sports,
                style: TextStyle(
                  fontWeight: FontWeight.w500, fontSize: 14,
                  // fontFamily: 'PingFangSC-Regular, PingFang SC'
                ),
              )
            ],
          ),
        ),
        sliver: SliverGrid(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              crossAxisSpacing: 8,
              mainAxisSpacing: 10,
              mainAxisExtent: 32),
          delegate: SliverChildBuilderDelegate(
            (context, i) => _item(widget.data.matchList[i]),
            childCount: widget.data.matchList.length,
          ),
        ),
      ),
    );
  }

  Widget _stateSection() {
    Widget _item(EventStateData model) {
      return GestureDetector(
          onTap: ClickUtils.debounce(() {
            if (selectState.id != model.id) {
              selectState = model;
              setState(() {});
            }
          }),
          child: Column(
            children: [
              Expanded(
                child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(4),
                      color: (selectState.id == model.id)
                          ? ThemeColor.primaryColor
                          : Color(0xffF4F4F4),
                    ),
                    alignment: Alignment.center,
                    child:
                        // Stack(
                        // children: [
                        //   Positioned(
                        //       top: 6,
                        //       right: 0,
                        //       left: 0,
                        //       child:
                        Text(
                      model.name,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: (selectState.id == model.id)
                            ? FontWeight.w600
                            : FontWeight.w400,
                        fontFamily: 'PingFangSC-Medium, PingFang SC',
                      ),
                      overflow: TextOverflow.ellipsis,
                    )
                    // ),
                    //     if (selectState.id == model.id)
                    //       Positioned(
                    //         right: 0,
                    //         bottom: 0,
                    //         child: Image.asset(
                    //           "assets/icons/icon_event_filter.png",
                    //           width: 16,
                    //           height: 13,
                    //         ),
                    //       ),
                    //   ],
                    // ),
                    ),
              ),
              SizedBox(
                height: 10,
              ),
            ],
          ));
    }

    return Container(
      child: SliverStickyHeader(
        header: Container(
          color: Colors.white,
          height: 42,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                S.of(context).State,
                style: TextStyle(
                    fontWeight: FontWeight.w500,
                    fontSize: 14,
                    fontFamily: 'PingFangSC-Regular, PingFang SC'),
              )
            ],
          ),
        ),
        sliver: SliverGrid(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              crossAxisSpacing: 8,
              mainAxisSpacing: 0,
              mainAxisExtent: 42),
          delegate: SliverChildBuilderDelegate(
            (context, i) => _item(widget.data.stateList[i]),
            childCount: widget.data.stateList.length,
          ),
        ),
      ),
    );
  }

  Widget _bottomView() {
    final mediaQueryData = MediaQuery.of(context);
    final width = (mediaQueryData.size.width - 45) / 2;
    return Container(
        height: 64.5,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(16),
              bottomRight: Radius.circular(16)),
        ),
        child: Column(
          children: [
            Divider(height: 0.5),
            SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Container(
                  width: width,
                  height: 40,
                  child: TextButton(
                    child: Text(
                      S.of(context).cancel,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w400,
                        color: ThemeColor.colorBlack100,
                      ),
                    ),
                    style: ButtonStyle(
                      shape: MaterialStateProperty.all(RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8))),
                      backgroundColor:
                          MaterialStateProperty.all(Color(0xffF4F4F4)),
                    ),
                    onPressed: ClickUtils.debounce(() {
                      _onCancel();
                    }),
                  ),
                ),
                Container(
                  width: width,
                  height: 40,
                  child: TextButton(
                      child: Text(
                        S.of(context).confirm,
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w400,
                          color: ThemeColor.colorBlack100,
                        ),
                      ),
                      style: ButtonStyle(
                        shape: MaterialStateProperty.all(RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8))),
                        backgroundColor:
                            MaterialStateProperty.all(ThemeColor.primaryColor),
                      ),
                      onPressed: ClickUtils.debounce(
                        () {
                          _onDone();
                        },
                      )),
                ),
              ],
            ),
            SizedBox(height: 12),
          ],
        ));
  }

  void _onDone() {
    widget.data.selectMatch = selectMatch;
    widget.data.selectState = selectState;
    widget.data.selectVenue = selectVenue;
    widget.data.callback();
  }

  void _onCancel() {
    widget.data.cancelCallBack();
  }
}

class EventStateData {
  final String name;
  final String id;
  EventStateData(this.name, this.id);
}

typedef void FunctionMapCallback();
typedef void FunctionCancel();

class EventFilterData {
  final FunctionMapCallback callback;
  final FunctionCancel cancelCallBack;
  List<VenueItem> venueList = [];
  List<GameDetail> matchList = [];
  List<EventStateData> stateList = [];
  List<DateTime> matchTimeList = [];
  VenueItem selectVenue = VenueItem({"id": "", "name": S().All, "code": ""});
  GameDetail selectMatch =
      GameDetail({"id": "", "discipline_name": S().All, "discipline": ""});
  EventStateData selectState = EventStateData(S().All, '0');
  EventFilterData(this.callback, this.cancelCallBack);
}
